// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/file/utils.h>
#include <pollux/common/base/exceptions.h>

namespace kumo::pollux::file::utils {
    bool CoalesceIfDistanceLE::operator()(
        const pollux::common::Region &a,
        const pollux::common::Region &b) const {
        POLLUX_CHECK_LE(a.offset, b.offset, "Regions to combine must be sorted.");
        const uint64_t beginGap = a.offset + a.length, endGap = b.offset;

        POLLUX_CHECK_LE(beginGap, endGap, "Regions to combine can't overlap.");
        const uint64_t gap = endGap - beginGap;

        const bool shouldCoalesce = gap <= maxCoalescingDistance_;
        if (coalescedBytes_ && shouldCoalesce) {
            *coalescedBytes_ += gap;
        }
        return shouldCoalesce;
    }
} // namespace kumo::pollux::file::utils
